<template>
  <div class="simple-order-management">
    <h2>客房订单管理</h2>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchText"
          placeholder="搜索订单号或客户姓名"
          style="width: 300px"
          clearable
      ></el-input>
      <el-button type="primary" @click="addOrder">新增订单</el-button>
    </div>
    <!-- 订单表格 -->
    <el-table :data="filteredOrders" border style="width: 100%">
      <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
      <el-table-column prop="customerName" label="客户姓名" width="120"></el-table-column>
      <el-table-column prop="roomType" label="房间类型" width="120"></el-table-column>
      <el-table-column prop="roomNumber" label="房间号" width="100"></el-table-column>
      <el-table-column prop="checkInDate" label="入住日期" width="120"></el-table-column>
      <el-table-column prop="checkOutDate" label="离店日期" width="120"></el-table-column>
      <el-table-column prop="totalPrice" label="总价" width="120">
        <template #default="{row}">
          ¥{{ row.totalPrice.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{row}">
          <el-tag :type="statusColor(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{row}">
          <el-button size="small" @click="editOrder(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOrder(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增/编辑订单对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="currentOrder" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input v-model="currentOrder.customerName"></el-input>
        </el-form-item>
        <el-form-item label="房间类型">
          <el-select v-model="currentOrder.roomType" placeholder="请选择">
            <el-option label="标准间" value="标准间"></el-option>
            <el-option label="大床房" value="大床房"></el-option>
            <el-option label="豪华套房" value="豪华套房"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="currentOrder.roomNumber"></el-input>
        </el-form-item>
        <el-form-item label="入住日期">
          <el-date-picker v-model="currentOrder.checkInDate" type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="离店日期">
          <el-date-picker v-model="currentOrder.checkOutDate" type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="总价">
          <el-input-number
              v-model="currentOrder.totalPrice"
              :min="0"
              :precision="2"
              :step="100"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentOrder.status" placeholder="请选择">
            <el-option label="已预订" value="已预订"></el-option>
            <el-option label="已入住" value="已入住"></el-option>
            <el-option label="已退房" value="已退房"></el-option>
            <el-option label="已取消" value="已取消"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </template>
    </el-dialog>
    <!-- 加载中 -->
    <el-loading v-model="loading" text="加载中..."></el-loading>
    <!-- 消息提示 -->
    <el-message :message="message" :type="messageType" :duration="3000" v-if="message"></el-message>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'

// 设置后端接口基础URL
axios.defaults.baseURL = 'http://localhost:8080/api/orders'

export default {
  name: 'SimpleOrderManagement',
  setup() {
    // 订单数据
    const orders = ref([])
    // 搜索文本
    const searchText = ref('')
    // 对话框状态
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增订单')
    const isEditing = ref(false)
    // 当前订单
    const currentOrder = ref({
      id: null,
      orderNo: '',
      customerName: '',
      roomType: '',
      roomNumber: '',
      checkInDate: '',
      checkOutDate: '',
      totalPrice: 0,
      status: '已预订'
    })
    // 过滤后的订单
    const filteredOrders = computed(() => {
      if (!searchText.value) return orders.value
      return orders.value.filter(order =>
          order.orderNo.includes(searchText.value) ||
          order.customerName.includes(searchText.value)
      )
    })
    // 状态标签颜色
    const statusColor = (status) => {
      const colors = {
        '已预订': 'warning',
        '已入住': 'success',
        '已退房': 'info',
        '已取消': 'danger'
      }
      return colors[status] || ''
    }
    // 生成订单号
    const generateOrderNo = () => {
      return `ORD${Date.now()}`
    }
    // 加载状态
    const loading = ref(false)
    // 消息提示
    const message = ref('')
    const messageType = ref('success')

    const fetchOrders = async (page = 0, size = 10) => {
      loading.value = true;
      try {
        const response = await axios.get('', {
          params: { page, size }
        });
        orders.value = response.data.content;
        console.log(orders.value);
      } catch (error) {
        console.error('获取订单失败', error);
        message.value = '获取订单失败，请稍后重试';
        messageType.value = 'error';
      } finally {
        loading.value = false;
      }
    };

    // 显示消息提示
    const showMessage = (msg, type = 'success') => {
      message.value = msg
      messageType.value = type
      setTimeout(() => {
        message.value = ''
      }, 3000)
    }

    // 新增订单
    const addOrder = () => {
      dialogTitle.value = '新增订单'
      isEditing.value = false
      currentOrder.value = {
        id: null,
        orderNo: generateOrderNo(),
        customerName: '',
        roomType: '',
        roomNumber: '',
        checkInDate: '',
        checkOutDate: '',
        totalPrice: 0,
        status: '已预订'
      }
      dialogVisible.value = true
    }

    // 编辑订单
    const editOrder = (order) => {
      dialogTitle.value = '编辑订单'
      isEditing.value = true
      currentOrder.value = {...order}
      dialogVisible.value = true
    }

    // 删除订单
    const deleteOrder = async (order) => {
      loading.value = true
      try {
        await axios.delete(`/${order.id}`)
        fetchOrders()
        showMessage('订单删除成功')
      } catch (error) {
        console.error('删除订单失败', error)
        showMessage('订单删除失败，请稍后重试', 'error')
      } finally {
        loading.value = false
      }
    }

    // 保存订单
    const saveOrder = async () => {
      loading.value = true
      try {
        if (isEditing.value) {
          // 更新订单
          await axios.put(`/${currentOrder.value.id}`, currentOrder.value)
          showMessage('订单更新成功')
        } else {
          // 新增订单
          await axios.post('', currentOrder.value)
          showMessage('订单创建成功')
        }
        dialogVisible.value = false
        fetchOrders()
      } catch (error) {
        console.error('保存订单失败', error)
        showMessage('订单保存失败，请稍后重试', 'error')
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      fetchOrders()
    })

    return {
      orders,
      searchText,
      filteredOrders,
      dialogVisible,
      dialogTitle,
      currentOrder,
      statusColor,
      addOrder,
      editOrder,
      deleteOrder,
      saveOrder,
      loading,
      message,
      messageType
    }
  }
}
</script>

<style scoped>
.simple-order-management {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
</style>